package com.example.springboot_zhenhong.exception;

import com.example.springboot_zhenhong.pojo.ResponseMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice //统一处理
public class GlobalExceptionHandlerAdvice {

    Logger log = LoggerFactory.getLogger(GlobalExceptionHandlerAdvice.class);
    @ExceptionHandler({Exception.class}) //什么异常的统一处理
    public ResponseMessage handlerException(Exception e, HttpServletRequest httpServletRequest,
                                            HttpServletResponse httpServletResponse){
        //记录日志
        log.error("统一异常",e);
        return new ResponseMessage(500,"error",null);
    }

    @ExceptionHandler({MethodArgumentNotValidException.class}) //方法参数异常的统一处理
    public ResponseMessage handlerMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest httpServletRequest,
                                            HttpServletResponse httpServletResponse){
        // 获取异常信息 BindingResult
        BindingResult exceptions = e.getBindingResult();
        // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
        if (exceptions.hasErrors()) {
            List<ObjectError> allErrors = exceptions.getAllErrors();
            if (allErrors.size() > 0) {
                // 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
                ObjectError objectError = allErrors.get(0);
                return new ResponseMessage(500,objectError.getDefaultMessage(),null);
            }
        }
        return new ResponseMessage(500,"error",null);
    }
}
